
import OpenAI from "openai";
import fs from 'fs';
import path from 'path';
import pLimit from 'p-limit';
import dotenv from 'dotenv';
import cliProgress from 'cli-progress';
import * as cheerio from 'cheerio';

dotenv.config();

const openai = new OpenAI({
    baseURL: process.env.OPEN_API,
    apiKey: process.env.OPEN_API_KEY,
});

// 日志文件路径
const logFilePath = path.join(process.cwd(), 'translation_log.txt');

// 记录翻译日志
function logTranslation(originalText, translatedText) {
    const timestamp = new Date().toISOString();
    const logEntry = `[${timestamp}] Original: ${originalText}\nTranslated: ${translatedText}\n\n`;
    fs.appendFileSync(logFilePath, logEntry);
}

export async function translateText(text) {


    if (!text.trim()) {
        return '';
    }

    const completion = await openai.chat.completions.create({
        messages: [{
            "role": "system",
            "content": "你是一个中英文翻译专家，你现在需要将翻译一个开源库Cesiumjs的文档。大概介绍一下Cesium，Cesium是一个前端Gis方面的第三方库，所以在一些必要时你结合对应场景来回答用户。你只需要将翻译的结果返回，不需要返回其他信息，切记。"
        },
        {
            "role": "user",
            "content": text.trim()
        }],
        model: "deepseek-chat",
    });

    const translatedText = completion.choices[0].message.content;
    // console.log(translatedText)
    // const $ = cheerio.load(translatedText,{ decodeEntities: true });

    // const result = $.text()

    // 记录翻译日志
    logTranslation(text, translatedText);

    return translatedText;
}
const progressBar = new cliProgress.SingleBar({
    format: '翻译进度 |{bar}| {percentage}% | {value}/{total} 条 | 用时: {duration}s',
    barCompleteChar: '\u2588',
    barIncompleteChar: '\u2591',
    hideCursor: true
}, cliProgress.Presets.shades_grey);


export async function translateTextArray(textArray, concurrency = 5) {
    if (!Array.isArray(textArray)) {
        return [];
    }

    const limit = pLimit(concurrency);
    let completed = 0;
    
    progressBar.start(textArray.length, 0);

    const translationPromises = textArray.map(item => {
        return limit(() => translateText(item)
            .then(result => {
                completed++;
                progressBar.update(completed);
                return result;
            }));
    });

    try {
        const translatedTexts = await Promise.all(translationPromises);
        progressBar.stop();
        return translatedTexts;
    } catch (error) {
        progressBar.stop();
        throw error;
    }
}

export function isHtmlFile(url) {
    const filename = url.split('?')[0].split('#')[0]; // 移除 ?query 和 #hash
    return filename.toLowerCase().endsWith('.html') || 
           filename.toLowerCase().endsWith('.htm');
  }